<template>
  <div class="type-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>类型管理</span>
          <el-button type="primary" @click="handleAdd">新增类型</el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="类型名称">
          <el-input v-model="searchForm.name" placeholder="请输入类型名称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 类型列表 -->
      <el-table :data="filteredTypes" style="width: 100%" v-loading="loading">
        <el-table-column prop="tid" label="ID" width="80" />
        <el-table-column prop="tname" label="类型名称" />
        <el-table-column prop="tremarks" label="描述" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="!row.tdelete ? 'success' : 'danger'">
              {{ !row.tdelete ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button 
              :type="!row.tdelete ? 'danger' : 'success'" 
              size="small" 
              @click="handleToggleStatus(row)">
              {{ !row.tdelete ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 编辑/新增对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增类型' : '编辑类型'"
      width="500px"
    >
      <el-form :model="typeForm" :rules="rules" ref="typeFormRef" label-width="80px">
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="typeForm.name" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item label="描述" prop="mark">
          <el-input 
            v-model="typeForm.mark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入类型描述" 
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="typeForm.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { addType, deleteTypeById, updateType, findAllTypes } from '@/api/type'
onMounted(() => {
  TypeList()
})
// 数据
const loading = ref(false)
const types = ref([])
const searchForm = reactive({
  name: '',
  status: ''
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const typeFormRef = ref()
const typeForm = reactive({
  id: null,
  name: '',
  mark: '',
  status: 'active',
})
// 类型列表
const TypeList = () => {
  loading.value = true
  findAllTypes().then(res => {
    console.log('类型列表响应:', res)
    // 兼容不同的响应格式
    if (res && res.data) {
      types.value = res.data
    } else if (Array.isArray(res)) {
      types.value = res
    } else if (res && Array.isArray(res.list)) {
      types.value = res.list
    } else {
      types.value = []
      console.warn('未知的响应格式:', res)
    }
    loading.value = false
  }).catch(error => {
    console.error('获取类型列表失败:', error)
    ElMessage.error('获取类型列表失败')
    loading.value = false
  })
}
// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入类型名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  mark: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}


// 计算属性：过滤后的类型列表
const filteredTypes = computed(() => {
  let result = types.value

  // 搜索过滤
  if (searchForm.name) {
    result = result.filter(item => 
      item.tname.toLowerCase().includes(searchForm.name.toLowerCase())
    )
  }
  if (searchForm.status) {
    result = result.filter(item => {
      const itemStatus = !item.tdelete ? 'active' : 'inactive'
      return itemStatus === searchForm.status
    })
  }

  // 分页
  total.value = result.length
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return result.slice(start, end)
})

// 方法


const handleSearch = () => {
  currentPage.value = 1
}

const handleReset = () => {
  searchForm.name = ''
  searchForm.status = ''
  currentPage.value = 1
}

const handleSizeChange = (val) => {
  pageSize.value = val
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(typeForm, {
    id: null,
    name: '',
    mark: '',
    status: 'active',
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  // 将后端字段映射到前端的typeForm格式
  const mappedRow = {
    id: row.tid,
    name: row.tname,
    mark: row.tremarks,
    status: !row.tdelete ? 'active' : 'inactive'
  }
  Object.assign(typeForm, mappedRow)
  dialogVisible.value = true
}

const handleToggleStatus = (row) => {
  const action = !row.tdelete ? '禁用' : '启用'
  const newTdelete = !row.tdelete
  
  ElMessageBox.confirm(
    `确定要${action}类型"${row.tname}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 创建更新数据，只修改状态
    const updateData = {
      ...row,
      tdelete: newTdelete
    }
    
    updateType(updateData).then(res => {
      console.log('更新类型状态响应:', res)
      // 兼容不同的响应格式
      if (res === '修改成功' || (res && res.message === '修改成功') || (res && res.status === 200)) {
        row.tdelete = newTdelete
        ElMessage.success(`${action}成功`)
      } else {
        ElMessage.error(res.message || `${action}失败`)
      }
    }).catch(error => {
      console.error('更新类型状态失败:', error)
      ElMessage.error(`${action}失败`)
    })
  }).catch(() => {})
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除类型"${row.tname}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteTypeById(row.tid).then(res => {
      console.log('删除类型响应:', res)
      // 兼容不同的响应格式
      if (res === '删除成功' || (res && res.message === '删除成功') || (res && res.status === 200)) {
        ElMessage.success('删除成功')
        // 重新获取列表
        TypeList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    }).catch(error => {
      console.error('删除类型失败:', error)
      ElMessage.error('删除类型失败')
    })
  }).catch(() => {})
}

const handleSubmit = () => {
  typeFormRef.value.validate((valid) => {
    if (valid) {
      if (dialogType.value === 'add') {
        // 新增
        // 将前端字段映射到后端格式
        const backendData = {
          tname: typeForm.name,
          tremarks: typeForm.mark,
          tdelete: typeForm.status === 'inactive'
        }
        addType(backendData).then(res => {
          console.log('新增类型响应:', res)
          // 兼容不同的响应格式
          if (res === '添加成功' || (res && res.message === '添加成功') || (res && res.status === 200)) {
            ElMessage.success('新增成功')
            dialogVisible.value = false
            TypeList() // 重新获取列表
          } else {
            ElMessage.error(res.message || '新增失败')
          }
        }).catch(error => {
          console.error('新增类型失败:', error)
          ElMessage.error('新增类型失败')
        })
      } else {
        // 编辑
        // 将前端字段映射到后端格式
        const backendData = {
          tid: typeForm.id,
          tname: typeForm.name,
          tremarks: typeForm.mark,
          tdelete: typeForm.status === 'inactive'
        }
        updateType(backendData).then(res => {
          console.log('更新类型响应:', res)
          // 兼容不同的响应格式
          if (res === '修改成功' || (res && res.message === '修改成功') || (res && res.status === 200)) {
            ElMessage.success('编辑成功')
            dialogVisible.value = false
            TypeList() // 重新获取列表
          } else {
            ElMessage.error(res.message || '编辑失败')
          }
        }).catch(error => {
          console.error('更新类型失败:', error)
          ElMessage.error('更新类型失败')
        })
      }
    }
  })
}

// 生命周期
onMounted(() => {
  TypeList()
})

// 移除未使用的变量警告
// eslint-disable-next-line no-unused-vars
const mockTypes = []
</script>

<style scoped>
.type-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>